﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using xClient.Framework;
using xClient.Framework.BaseView;
using xClient.Framework.PlugCore;
using xClient.Framework.StaticResource;

namespace cMES1007
{
    public partial class frmESOPEdit : Form
    {
        private DataGridViewRow _dgvRow = null;
        private object _sopDetail = null;

        private string _strCmd = "ADD";
        public frmESOPEdit(string vCMD, object param = null)
        {
            InitializeComponent();
            //initial group name list;
            InitialGroupNameList();

            this._strCmd = vCMD;
            this.ClearFormInputData(this._strCmd, param);
        }

        private void InitialViewData()
        {
            if (this._dgvRow != null)
            {
                this.txtESOPID.Visible = true;
                this.txtESOPID.Visible = true;
                this.txtESOPID.Text = _dgvRow.Cells[0].Value.ToString();
                this.txtSOPName.Text = _dgvRow.Cells[1].Value.ToString();
                this.cmbGroupName.Text = _dgvRow.Cells[2].Value.ToString();
                this.txtSKUName.Text = _dgvRow.Cells[3].Value.ToString();
                this.txtOperationStep.Text = _dgvRow.Cells[4].Value.ToString();
                this.txtSOPDescription.Text = _dgvRow.Cells[5].Value.ToString();
                this.txtRemarks.Text = _dgvRow.Cells[6].Value.ToString();
                this.txtIsValid.Text = _dgvRow.Cells[7].Value.ToString();
                this.txtCreateUser.Text = _dgvRow.Cells[9].Value.ToString();
                this.dtpCreateTime.text = _dgvRow.Cells[8].Value.ToString();
                this.txtUpdateUser.Text = _dgvRow.Cells[10].Value.ToString();
                this.dtpUpdateTime.text = _dgvRow.Cells[11].Value.ToString();
                if (_dgvRow.Cells[12].Value != null)
                {
                    _sopDetail = _dgvRow.Cells[12].Value;

                    this.FillDGVManual(_sopDetail);
                }
            }
        }

        private void ClearFormInputData(string vCMD,object param =null)
        {
            this.txtESOPID.Enabled = false;
            if (_strCmd.ToUpper().Equals("ADD"))
            {
                this.Text = "新增ESOP信息";
                this.txtESOPID.Text = "";
                this.txtSOPName.Text = "";
                this.cmbGroupName.Text = "";
                this.txtSKUName.Text = "";
                this.txtOperationStep.Text = "";
                this.txtSOPDescription.Text = "";
                this.txtRemarks.Text = "";
                this.txtCreateUser.Enabled = false;
                this.txtCreateUser.Text = StaticDictionary.Dictionary.UserID;
                this.txtUpdateUser.Text = "";
                this.txtUpdateUser.Enabled = false;
                this.dtpCreateTime.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                this.txtSOPName.Focus();
                this.datalist.Rows.Clear();
            }
            else if (_strCmd.ToUpper().Equals("EDIT"))
            {
                this.Text = "修改ESOP信息";
                if (param != null)
                {
                    this._dgvRow = (DataGridViewRow)param;
                }
                this.InitialViewData();

                this.txtUpdateUser.Text = StaticDictionary.Dictionary.UserID;
                this.dtpUpdateTime.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckInputValidate())
            {
                return;
            }
            #region 初始化SOP数据
            var param = new
            {
                id = this.txtESOPID.Text.Trim(),
                sop_name = this.txtSKUName.Text.Trim().ToUpper(),
                group_name = this.cmbGroupName.Text.Trim().ToUpper(),
                sku_name = this.txtSKUName.Text.Trim().ToUpper(),
                operation_step = this.txtOperationStep.Text.Trim().ToUpper(),
                description = this.txtSOPDescription.Text.Trim(),
                remarks = this.txtRemarks.Text.Trim(),
                create_user = this.txtCreateUser.Text.Trim(),
                create_time = this.dtpCreateTime.Text,
                update_user = this.txtUpdateUser.Text.Trim(),
                update_time = this.dtpUpdateTime.Text,
                is_valid = this.txtIsValid.Text,
                sop_details = this.InitialESOPDetailInfo()
            };
            if (this.datalist.Rows.Count <= 0)
            {
                DialogResult _dialogRes = MessageBox.Show("还没添加操作明细，是否确认添加", "提交确认",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                if (_dialogRes == DialogResult.No)
                {
                    return;
                }
            }
            #endregion
            var dataModel = JsonConvert.SerializeObject(param);
            ExecutionResult<dynamic> result = new ExecutionResult<dynamic>();
            if (this._strCmd.Equals("ADD"))
            {
                result = Services.ServiceMethod.AddESOPInfo(dataModel);
            }
            else if (this._strCmd.Equals("EDIT"))
            {
                result  = Services.ServiceMethod.UpdateESOPInfo(dataModel);
            }

            if (result.Status)
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show(result.Message, "系统消息");
                return;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private bool CheckInputValidate()
        {
            bool _bResult = true;
            if (String.IsNullOrEmpty(this.cmbGroupName.Text.Trim()))
            {
                MessageBox.Show("站别必须输入.");
                return false;
            }
            if (String.IsNullOrEmpty(this.txtSKUName.Text.Trim()))
            {
                MessageBox.Show("产品型号必须输入.");
                return false;
            }
            return _bResult;
        }

        private void InitialGroupNameList()
        {
            var result = Services.ServiceMethod.GetGroupNameList();
            if (result.Status)
            {
                this.cmbGroupName.DataSource = result.Data;
                this.cmbGroupName.ValueMember = "group_name";
                this.cmbGroupName.DisplayMember = "group_name";
            }
        }

        private List<dynamic> InitialESOPDetailInfo()
        {
            List<dynamic> lstRes = new List<dynamic>();

            if(this.datalist.Rows.Count > 0)
            {
                foreach(DataGridViewRow tmpRow in this.datalist.Rows)
                {
                    if(tmpRow != null && tmpRow.Cells[3].Value!=null)
                    {
                        var tmpDetails = new
                        {
                            id = tmpRow.Cells["id"].Value.ToString(),
                            sop_name_id = this.txtESOPID.Text.Trim(),
                            step_name = tmpRow.Cells["step_name"].Value.ToString(),
                            sop_detail_description = tmpRow.Cells["sop_detail_description"].Value.ToString(),
                            sequence = tmpRow.Cells["sequence"].Value.ToString(),
                            is_valid = tmpRow.Cells["is_valid"].Value.ToString(),
                            create_user = tmpRow.Cells["create_user"].Value.ToString(),
                            create_time = tmpRow.Cells["create_time"].Value.ToString(),
                            update_user = tmpRow.Cells["update_user"].Value.ToString(),
                            update_time = tmpRow.Cells["update_time"].Value.ToString(),
                            sop_images = tmpRow.Cells["sop_images"].Value
                        };
                        lstRes.Add(tmpDetails);
                    }
                }
            }

            return lstRes;
        }

        private void btnDetailAdd_Click(object sender, EventArgs e)
        {
            this.ESOPDetailChange(sender);
        }

        private void btnDetailModify_Click(object sender, EventArgs e)
        {
            this.ESOPDetailChange(sender);
        }

        private void btnDetailDelete_Click(object sender, EventArgs e)
        {

            if (this.datalist.SelectedRows.Count > 0)
            {
               DialogResult _diaRes =  MessageBox.Show("此时删除，将在您最终保存后删除系统中的数据。", "系统提示",
                     MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                if(_diaRes == DialogResult.Yes)
                {
                    this.datalist.Rows.Remove(this.datalist.SelectedRows[0]);
                    MessageBox.Show("数据清除成功");
              }
            }
        }

        private void datalist_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                MessageBox.Show("请选择一笔ESOP操作详情记录.");
                return;
            }
            DataGridViewRow _dgvRow = datalist.SelectedRows[0];
            frmESOPDetailAndImgEdit _frmDetailEdit = new frmESOPDetailAndImgEdit("EDIT", _dgvRow);

            DialogResult _diaRes = _frmDetailEdit.ShowDialog();
            if(_diaRes == DialogResult.Yes)
            {
                MessageBox.Show("修改SOP详细信息成功.");
                //删除当前表格中的操作记录
                this.datalist.Rows.Remove(_dgvRow);
                //将修改后的操作记录增加到当前表格
                this.datalist.Rows.Add(_frmDetailEdit._dgvChangeRow);
            }          
        }

        private void ESOPDetailChange(object sender)
        {
            frmESOPDetailAndImgEdit _frmDetailEdit = default(frmESOPDetailAndImgEdit);
            var clickBtnTag = ((ToolStripButton)sender).Tag;
            DataGridViewRow _selectData = null;
            if (clickBtnTag.Equals("ADD"))
            {
                int index = this.datalist.Rows.Add();
                _selectData = this.datalist.Rows[index];
            }
            if (clickBtnTag.Equals("EDIT"))
            {
                if(this.datalist.Rows.Count < 1)
                {
                    return;
                }
                if (this.datalist.SelectedRows.Count < 1)
                {
                    MessageBox.Show("请选择一笔需要修改的资料.", "系统提醒", MessageBoxButtons.OK,
                         MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    return;
                }
                if (this.datalist.SelectedRows.Count > 0)
                {
                    _selectData = this.datalist.SelectedRows[0];
                }
            }
            _frmDetailEdit = new frmESOPDetailAndImgEdit(clickBtnTag.ToString(), _selectData);
            _frmDetailEdit.iMaxSeq = this.GetMaxDetailSquence();
            _frmDetailEdit._strSKUName = this.txtSKUName.Text.Trim().ToUpper();

            DialogResult _diaRes = _frmDetailEdit.ShowDialog();
            if (_diaRes == DialogResult.OK)
            {
                if (clickBtnTag.Equals("ADD"))
                {
                    MessageBox.Show("数据新增成功..","系统提示");
                }
                else
                {
                    MessageBox.Show("数据修改成功..","系统提示");
                    //remove current data rows
                    this.datalist.Rows.Remove(_selectData);
                    //add new rows
                    this.datalist.Rows.Add(_frmDetailEdit._dgvChangeRow);
                }
            }
            else if (_diaRes == DialogResult.No)
            {
                if (clickBtnTag.Equals("ADD"))
                {
                    MessageBox.Show("数据新增失败..");
                }
                else
                {
                    MessageBox.Show("数据修改失败..");
                }
            }
            else if(_diaRes == DialogResult.Cancel)
            {
                //remove current data rows
                this.datalist.Rows.Remove(_selectData);
            }

        }

        private int GetMaxDetailSquence()
        {
            int result = 0;
            if (this.datalist.Rows.Count > 0)
            {
                foreach(DataGridViewRow tmpRow in this.datalist.Rows)
                {
                    int _iTmpSeq = Convert.ToInt32(tmpRow.Cells["sequence"].Value);
                    if (_iTmpSeq > result)
                    {
                        result = _iTmpSeq;
                    }
                }
            }
            return result;
        }

        private void FillDGVManual(dynamic sopDetails)
        {
            if(sopDetails != null)
            {
                this.datalist.Rows.Clear();
                foreach(var tmpDetail in sopDetails)
                {
                    int rowIndx = this.datalist.Rows.Add();
                    DataGridViewRow tmpRow = this.datalist.Rows[rowIndx];
                    tmpRow.Cells[0].Value = tmpDetail.id;
                    tmpRow.Cells[1].Value = tmpDetail.sop_name_id;
                    tmpRow.Cells[2].Value = tmpDetail.step_name;
                    tmpRow.Cells[3].Value = tmpDetail.sop_detail_description;
                    tmpRow.Cells[4].Value = tmpDetail.sequence;
                    tmpRow.Cells[5].Value = tmpDetail.is_valid;
                    tmpRow.Cells[6].Value = tmpDetail.create_user;
                    tmpRow.Cells[7].Value = tmpDetail.create_time;
                    tmpRow.Cells[8].Value = tmpDetail.update_user;
                    tmpRow.Cells[9].Value = tmpDetail.update_time;
                    tmpRow.Cells[10].Value = tmpDetail.sop_images;                    
                }
            }
        }
    }
}
